/**
 *
 *	Depends on:
 *		jQuery
 *		jQuery UI
 */
$(document).ready(function() {

	//Selectors and Statics
	var QUESTION_LIST = $('#admin-question-list');
	var FORM = $('#remove-question-form');
	var REMOVE_QUESTION = $('.remove-question');

	var ERROR_MESSAGE = $('<div id="remove-error" class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Error!</strong> Unable to remove the question.</div>');

	/* Listener */
	REMOVE_QUESTION.on('click', function() {
		questionItem = $(this).closest('li');
		test_id = questionItem.attr('id');
		removeQuestion(test_id);
	});

	/**
	 *	Sends transform to exercise request with ajax.
	 */
	function removeQuestion(id) {
		$.ajax({
			type: 'POST',
			url: FORM.attr('action'),
			data: {'question_id': id},
			dataType: 'JSON',
			success: ajaxSuccess,
			error: ajaxError
		});
	}

	/**
	 * Called upon ajax success
	 */
	function ajaxSuccess(response) {
		questionId = response;
		QUESTION_LIST.find('#question_'+questionId).remove();

		errorAlert = $('#remove-error');
		if(errorAlert.length) {
			errorAlert.remove();
		}
	}

	/**
	 * Called upon ajax error
	 */
	function ajaxError(response) {
		if(! $('#remove-error').length) {
			FORM.append(ERROR_MESSAGE);
		}
	}	

});